#include "SchedulerInc.h"

using namespace bimar_scheduler_lib;

CJob::CJob(gboolean taskOwner /*= TRUE*/)
:m_taskOwner(taskOwner)
,m_executor(NULL)
,m_jobStatus(EStatus_Invalid)
{

}

CJob::~CJob()
{
  /* TODO: m_executor ... delete? */

  if(m_taskOwner)
    Delete();
}

gboolean CJob::PushBack(CTask *task)
{
  g_return_val_if_fail(task, FALSE);

  CGAutoLock lock(&m_taskListCS);
  m_taskList.push_back(task);

  return TRUE;
}

gboolean CJob::Remove(CTask *task)
{
  g_return_val_if_fail(task, FALSE);

  CGAutoLock lock(&m_taskListCS);    
  m_taskList.remove(task);    

  return TRUE;
}

gboolean CJob::Clear()
{
  CGAutoLock lock(&m_taskListCS);
  m_taskList.clear();

  return TRUE;
}

gboolean CJob::Delete()
{
  CGAutoLock lock(&m_taskListCS);
  
  for(TaskListIt it=m_taskList.begin(); it!=m_taskList.end(); it++)
  {
    CTask *task = *it;
    if(task)
      delete task;
  }
  m_taskList.clear();

  return TRUE;
}

gboolean CJob::IsEmpty()
{
  return (GetSize() == 0);
}

glong CJob::GetSize()
{
  CGAutoLock lock(&m_taskListCS);
  return (glong) m_taskList.size();
}

CTask * CJob::PopFront()
{    
  CGAutoLock lock(&m_taskListCS);
  
  TaskListIt it = m_taskList.begin();
  if(it == m_taskList.end())
    return NULL;

  CTask *task = *it;
  m_taskList.pop_front(); 

  return task;
}

CTask * CJob::Get(glong index)
{
  g_return_val_if_fail(index < GetSize(), NULL);

  CGAutoLock lock(&m_taskListCS);
  TaskListIt it;
  glong i=0;
  for(it=m_taskList.begin(); i<index; it++, i++);

  return (*it);
}

gboolean CJob::Run()
{
  g_return_val_if_fail(!m_executor, FALSE);
  
  gboolean ret = FALSE;
  while(1)
  {
	CGAutoLock lock(&m_executorCS);
    m_executor = new CJobExecutor;
	ret = m_executor->StartJob(this);
    break;
  }
  
  if(ret)
    m_executor->WaitJobDone();
  
  while(1)
  {
	CGAutoLock lock(&m_executorCS);
    delete m_executor, m_executor = NULL;
    break;
  }

  return ret;
}

gboolean CJob::Stop()
{
  g_return_val_if_fail(m_executor, FALSE);

  CGAutoLock lock(&m_executorCS);
  gboolean ret = m_executor->StopCurrentJob();

  return ret;
}

gboolean CJob::Pause()
{
  g_return_val_if_fail(m_executor, FALSE);

  CGAutoLock lock(&m_executorCS);
  gboolean ret = m_executor->PauseCurrentJob();

  return ret;
}

gboolean CJob::Resume()
{
  g_return_val_if_fail(m_executor, FALSE);

  CGAutoLock lock(&m_executorCS);
  gboolean ret = m_executor->ResumeCurrentJob();

  return ret;
}

gboolean CJob::Abort()
{
  g_return_val_if_fail(m_executor, FALSE);

  CGAutoLock lock(&m_executorCS);
  gboolean ret = m_executor->AbortCurrentJob();

  return ret;
}
